<template>
  <view class="container">
    <!-- <view class="nav-bar">
			<BackNav title="" bgColor="#E0EEFF" :show-back="false"></BackNav>
		</view> -->
    <!-- 修复顶部导航栏 - 使用原生flex布局替代uni-row/uni-col -->
    <view class="header-row" style="margin-top:15rpx;">
      <view class="header-col" style="flex: 0 0 20%;">
        <view style="display: flex;justify-content: center;align-items: center;padding:15rpx;">
          <!-- 使用原生picker替代uni-data-select -->
          <picker mode="selector" :range="gradeRange" :clearabled="true" range-key="text" :value="gradeRangeIndex"
            @change="classPickerChange">
            <view class="picker-view">{{ gradeRange[gradeRangeIndex]?.text || '选择年级' }}
            </view>
          </picker>
          <image class="arrow-icon" src="/static/version_4/Slice2.png" style="width: 30rpx;height: 30rpx;"></image>
        </view>
      </view>
      <view class="header-col" style="flex: 0 0 65%;">
        <Searcher :keyword="keyword" @update:keyword="keyword = $event" @search="onSearch" @click="uni.navigateTo({url:'/pages/index/searchPage'});"/>
      </view>
      <view class="header-col" style="flex: 0 0 15%;">
        <view style="display: flex;justify-content: center;align-items: center  ;padding:15rpx 0 ;">
          <image style="width:64rpx;height:64rpx;margin-left: 20rpx;" src="/static/version_4/Slice1.png"></image>
        </view>
      </view>
    </view>
    <swiper autoplay indicator-dots style="width:100%;height:300rpx;margin-top:15rpx;">
      <swiper-item style="width:100%;height:100%; display: flex;justify-content: center;">
        <image style="width:700rpx;height:100%;border-radius: 15rpx;;" src="/static/img/mall.png"></image>
      </swiper-item>
      <swiper-item style="width:100%;height:100%; display: flex;justify-content: center;">
        <image style="width:700rpx;height:100%;border-radius: 15rpx;;" src="/static/img/mall.png"></image>
      </swiper-item>
      <swiper-item style="width:100%;height:100%; display: flex;justify-content: center;">
        <image style="width:700rpx;height:100%;border-radius: 15rpx;;" src="/static/img/mall.png"></image>
      </swiper-item>
    </swiper>
    <view class="study-space">
      <view style="display: flex;justify-content: space-between;align-items: center; padding:30rpx 0rpx;">
        <view class="section-title">学习空间</view>
        <view @click="onMoreClick(1)"><text style="font-size: 24rpx; color: #999;">更多&nbsp;></text></view>
      </view>
      <view class="course-band">
        <scroll-view scroll-y class="course-scroll">
          <view class="course-row">
            <view v-for="(course, index) in courseList" :key="course.id" class="course-item"
              @click="goToCourse(course)">
              <image class="course-icon" :src="getCourseIcon(course.name)" mode="aspectFit" />
              <text class="course-name"
                style="width: 120rpx;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                {{ formatCourseName(course.name) }}
              </text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <view>
      <view style="display: flex;justify-content: space-between;align-items: center;padding:0rpx 30rpx 0rpx 0rpx;">
        <view style="width: 50%;">
          <u-tabs :list="[{ name: '名师讲堂' }, { name: '知识探索' }]" :current="currentTab" @change="handleTabChange"></u-tabs>
        </view>
        <view @click="onMoreClick(2)"><text style="font-size: 24rpx; color: #999;">更多&nbsp;></text></view>
      </view>
      <view style="width:100%;height:calc(100vh - 500rpx);">
        <!-- 使用原生scroll-view替代mescroll-uni -->
        <scroll-view class="video-scroll" scroll-y style="height: 100%;" @scrolltolower="loadMore">
          <view v-if="isEmpty" class="no-more">暂无数据...</view>
          <view v-else>
            <!-- 使用原生view替代uni-list和uni-list-item -->
            <view class="video-waterfall">
              <view v-for="video in videoList" :key="video.id" class="video-card" @click="onVideoItemClick(video)">
                <!-- 封面 16:9 -->
                <image class="cover" :src="video.coverUrl" mode="aspectFill" />
                <!-- 信息区 -->
                <view class="info">
                  <view class="name">
                    <u-tag type="primary" :text="video.subjectName" size="small" shape="square" />
                    <text>{{ video.videoTitle }}</text>
                  </view>
                  <!-- <view class="video-name text-ellipsis">{{ item.subjectName }}</view> -->
                  <view class="school-name text-ellipsis">{{ video.schoolName }}&nbsp;&nbsp;{{ video.teacherName }}
                  </view>
                  <!-- <view class="school-name text-ellipsis">{{ video.teacherName }}</view> -->
                </view>
              </view>
            </view>
          </view>
          <!-- 加载更多提示 -->
          <view v-if="loading" class="loading-more">加载中...</view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { useUserStore } from '@/stores/user'
import uniReq from '@/api/uniReq'
import Searcher from '@/components/searcher/searcher.vue'
import BackNav from '@/components/backNav/backNav.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

// 用户存储
const user = useUserStore()

// 班级选择索引
const keyword = ref('')
const currentTab = ref(0)
// 切换标签页
const handleTabChange = (index) => {
  currentTab.value = index
}
// 搜索图标路径
// const searchIcon = ref('/static/img/search.png')
const onSearch = (keyword) => {
  console.log('搜索关键词:', keyword)
  // keyword.value = keyword// 赋值给搜索关键词
  loadHomeData(keyword)
}

// 格式化课程名称 - 处理过长名称
const formatCourseName = (name) => {
  if (!name) return ''

  // 如果名称超过6个字符，进行缩短
  if (name.length > 6) {
    return name.substring(0, 5) + '...'
  }

  return name
}

// 响应式数据
const title = ref('首页')
const gradeRangeIndex = ref(0) // 班级选择索引
const gradeRange = ref([]) // 班级选项
// 获取年级
const getGradeRange = async () => {
  try {
    const res = await uniReq({
      url: '/grade/find-grade-id-and-name',
      method: 'GET'
    })
    if (res.status === 200) {
      gradeRange.value = res.data.map(item => ({
        value: item.gradeId,
        text: item.name
      }))
      console.log(uni.getStorageSync('userInfo'));
      const idx = gradeRange.value.findIndex(v => v.value === uni.getStorageSync('userInfo').gradeId)
      gradeId.value = uni.getStorageSync('userInfo').gradeId
      // console.log(idx);
      if (idx !== -1) {
        gradeRangeIndex.value = idx
      }
    }
  } catch (error) {
    console.error('获取年级失败:', error)
  }
}

// 学习空间课程列表
const courseList = ref<any[]>([])

// 名师讲堂视频列表
const videoList = ref<any[]>([])
const isEmpty = ref(false)
const loading = ref(false)

// 课程图标映射
const courseIcons = {
  "语文": "/static/version_4/Slice3.png",
  "数学": "/static/version_4/Slice4.png",
  "英语": "/static/version_4/Slice5.png",
  "物理": "/static/version_4/Slice6.png",
  "化学": "/static/version_4/Slice7.png",
  "生物": "/static/version_4/Slice12.png",
  "生物学": "/static/version_4/Slice36.png",

  "地理": "/static/version_4/Slice8.png",
  "历史": "/static/version_4/Slice9.png",

  "政治": "/static/version_4/Slice10.png",
  "道德与法治": "/static/version_4/Slice35.png",
  "思想政治": "/static/version_4/Slice10.png",


  "体育": "/static/version_4/Slice11.png",
  "体育与健康": "/static/version_4/Slice38.png",

  "信息技术": "/static/version_4/Slice40.png",
  "通用技术": "/static/version_4/Slice31.png",

  "音乐": "/static/version_4/Slice41.png",
  "美术": "/static/version_4/Slice37.png",
  "劳动": "/static/version_4/Slice33.png",
  "综合实践活动": "/static/version_4/Slice8.png",
  "科学": "/static/version_4/Slice6.png",
}

// 分页参数
const pageParams = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  hasMore: true
})

// 格式化视频列表为双列布局
const formattedVideoList = computed(() => {
  const formatted: any[] = []
  for (let i = 0; i < videoList.value.length; i += 2) {
    const item: any = {
      left: videoList.value[i]
    }
    if (i + 1 < videoList.value.length) {
      item.right = videoList.value[i + 1]
    }
    formatted.push(item)
  }
  return formatted
})

// 获取课程图标
const getCourseIcon = (courseName: string) => {
  return courseIcons[courseName] || "/static/version_4/Slice 3@3x.png"
}

// 班级选择变化
const gradeId = computed(() => gradeRange.value[gradeRangeIndex.value]?.value || '')
const classPickerChange = (e: any) => {
  gradeRangeIndex.value = e.detail.value
  console.log('班级选择变化:', gradeRange.value[gradeRangeIndex.value])
  // 重新加载数据
  refresh()
}

// 跳转到搜索页面
const toSearch = () => {
  uni.navigateTo({
    url: '/pages/search/search'
  })
}

// 课程点击事件
const onCourseClick = (course: any) => {
  console.log('点击课程:', course)
  uni.navigateTo({
    url: `/pages/course/course-detail?id=${course.subjectId}&name=${course.name}`
  })
}

// 更多点击事件
const onMoreClick = (type: number) => {
  console.log('点击更多:', type)
  //暂时先跳一个页面
  uni.navigateTo({
    url: '/pages/videoDetail/videoList'
  })
}

// 视频项点击事件
const onVideoItemClick = (video: any) => {
  console.log('点击视频:', video)
  if (video && video.videoPcId) {
    uni.navigateTo({
      url: `/pages/videoDetail/videoDetail?data=${encodeURIComponent(JSON.stringify(video))}`
    })
  }
}

// 下拉刷新
const refresh = () => {
  pageParams.page = 1
  pageParams.hasMore = true
  loadHomeData()
}

// 上拉加载更多
const loadMore = () => {
  if (!pageParams.hasMore || loading.value) return
  pageParams.page++
  loadHomeData()
}

const goToCourse = (course: any) => {
  console.log('点击课程:', course)
  uni.navigateTo({
    url: `/pages/videoDetail/videoList?id=${course.subjectId}&name=${course.name}&gradeId=${gradeRange.value[gradeRangeIndex.value]?.value || ''}`
  })
}

// 加载首页数据
const loadHomeData = async (keyword?) => {
  if (loading.value) return
  loading.value = true
  try {
    const res = await uniReq({
      url: '/video-content/app-index', // 假设接口地址为/home/data
      method: 'post',
      data: {
        page: pageParams.page,
        pageSize: pageParams.pageSize,
        gradeId: gradeId.value,
        keyWords: keyword || ''
      }
    })

    if (res.status === 200 && res.data) {
      const { subjects, videoContent } = res.data
      // 更新学科列表
      courseList.value = subjects || []
      console.log(courseList.value);
      // 更新视频列表
      if (pageParams.page === 1) {
        videoList.value = videoContent.list || []
      } else {
        videoList.value = [...videoList.value, ...(videoContent.list || [])]
      }

      pageParams.hasMore = (videoContent.list || []).length >= pageParams.pageSize
      isEmpty.value = videoList.value.length === 0
    } else {
      uni.showToast({
        title: res.message || '加载失败',
        icon: 'none'
      })
      return
    }
  } catch (error) {
    console.error('加载首页数据失败:', error)
    uni.showToast({
      title: error || '加载首页数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onShow(async () => {
  // 1. 先拉年级
  await getGradeRange();
  // 2. 年级到位后再赋默认值 & 加载首页
  // if (gradeRange.value.length > 0) {
  //   gradeRangeIndex.value = 0;   // 默认选第一条
  // }
  await loadHomeData();          // 此时 gradeId 已有值
})
</script>

<style lang="scss" scoped>
.nav-bar {
  height: 110rpx;
}

.container {
  padding: 1rpx;
  background: linear-gradient(to bottom, #E0EEFF 0%, #ffffff 20%);
}

/* 头部布局样式 */
.header-row {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.header-col {
  display: flex;
  align-items: center;
}

/* 班级选择器样式 */
.picker-view {
  padding: 10rpx 0;
  //透明背景
  background: #E0EEFF;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  min-width: 120rpx;
  text-align: center;
}

/* 搜索栏样式 */
.search-bar {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15rpx 20rpx;
  background: #f5f5f5;
  border-radius: 25rpx;
  margin: 0 10rpx;
}

.search-placeholder {
  color: #999;
  font-size: 28rpx;
}

.search-icon {
  margin-left: 10rpx;
}

.text-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden
}

.video-scroll {
  height: 100%;
  white-space: nowrap;

  // 隐藏滚动条
  // scrollbar-width: none; /* Firefox */
  // -ms-overflow-style: none; /* Internet Explorer 10+ */
  ::-webkit-scrollbar {
    display: none;
  }
}

.video-list-row {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.video-waterfall {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20rpx;
  gap: 20rpx; // 列间距
}

.video-card {
  width: 48%; // 两列等宽
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
  transition: transform 0.2s;

  &:active {
    transform: scale(0.98);
  }

  .cover {
    width: 100%;
    height: 200rpx; // 16:9 比例
    border-radius: 12rpx 12rpx 0 0;
  }

  .info {
    padding: 0 15rpx;

    .name {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }

    .school-name {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
}

/* 文字省略号 */

.no-more {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #666;
  font-size: 26rpx;
}

/* 学习空间样式 */
.study-space {
  padding: 30rpx;
  background: #fff;
  // margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  // margin-bottom: 30rpx;
}

/* 课程网格布局 - 自适应8个和10个图标 */
.course-band {
  height: 230rpx;
  /* 固定高度 */
  width: 100%;
}

.course-scroll {
  height: 100%;
  white-space: nowrap;
  /* 横向不换行 */
  // 隐藏滚动条
  // scrollbar-width: none; /* Firefox */
  // -ms-overflow-style: none; /* Internet Explorer 10+ */

  ::-webkit-scrollbar {
    display: none;
  }
}

.course-row {
  display: flex;
  flex-wrap: wrap;
  /* 多行 flex */
  // height: 100%;
  align-items: center;
  justify-content: space-between;
  gap: 30rpx;
  /* 列间距 */
}

.course-item {
  width: 20%;
  /* 一行 10 个 → 10% */
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  /* 禁止压缩 */
}

.course-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 8rpx;
}

.course-name {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #333;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 750rpx) {
  .course-grid-8 .course-item {
    width: 25%;
  }

  .course-grid-10 .course-item {
    width: 20%;
  }
}

/* 课程名称过长处理 */
.course-name {
  max-width: 120rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  white-space: normal;
  max-height: 2.4em;
  line-height: 1.2em;
}

.arrowDown {
  /* 基础样式 - 确保元素有宽高 */
  // display: inline-block;
  width: 0;
  height: 0;

  /* 三角形核心样式 */
  border-left: 10rpx solid transparent;
  /* 左边透明边框 */
  border-right: 10rpx solid transparent;
  /* 右边透明边框 */
  border-top: 10rpx solid #333;
  /* 顶部边框形成三角形底边，颜色可自定义 */

  /* 可选：调整位置或对齐 */
  vertical-align: middle;
  margin-left: 4rpx;
}

.arrow-icon {
  display: inline;
  margin-left: -20rpx;
  margin-top: 10rpx;
}

:deep(.u-tag) {
  margin-right: 5rpx;
  // width: 60rpx;
  padding-left: 5rpx;
  height: 35rpx;
  line-height: 37rpx;
  font-size: 24rpx;
  text-align: center;
}
</style>
